import {
  Controller,
  Post,
  Body,
  Get,
  Patch,
  Param,
  ParseIntPipe,
  Delete,
  Query,
} from '@nestjs/common';
import { BooksService } from './books.service';
import { CommonObjectProps, CommonResponse } from '../../types/obj-type';
import { responseWrapper } from '../../utils';

@Controller('books')
export class BooksController {
  constructor(private readonly bookService: BooksService) {}

  @Post()
  async addBook(@Body() book: CommonObjectProps): Promise<CommonResponse> {
    try {
      const res = await this.bookService.addBook(book);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get()
  async books(@Query() query: any): Promise<CommonResponse> {
    try {
      const res = await this.bookService.books(query);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get(':id')
  async getBook(@Param('id', new ParseIntPipe()) id: number): Promise<CommonResponse> {
    try {
      const res = await this.bookService.getBook(id);
      if (!res) throw new Error('帖子不存在');
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Patch(':id')
  async update(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() data: CommonObjectProps,
  ): Promise<CommonResponse> {
    try {
      const res = await this.bookService.update(id, data);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Delete(':id')
  async delete(@Param('id', new ParseIntPipe()) id: number): Promise<CommonResponse> {
    try {
      const res = await this.bookService.delete(id);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }
}
